package com.example.graduation.util;

import com.example.graduation.entity.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

/**
 * @author Jeffery
 * Shiro工具类
 */
public class ShiroUtil {
    /**
     * 获取用户名，便于回显数据
     *
     * @return String
     */
    public static String getUserName() {
        User currentUser = getCurrentUser();
        return currentUser != null ? currentUser.getEmail() : null;
    }

    /**
     * 获取当前用户ID
     *
     * @return String
     */
    public static String getUserId() {
        return getCurrentUser() != null ? getCurrentUser().getId() : null;
    }

    /**
     * 获取当前用户
     *
     * @return user
     */
    public static User getCurrentUser() {
        Subject subject = getSubject();
        return (User) subject.getPrincipal();
    }

    /**
     * 获取Subject
     *
     * @return subject
     */
    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }


    /**
     * 登陆
     *
     * @param token token
     */
    public static void login(UsernamePasswordToken token) {
        getSubject().login(token);
    }


    /**
     * 注销当前用户
     */
    public static void exit() {
        getSubject().logout();
    }
}
